package javabase.concurrent;


public class VisibilityDemo {

    public static void main(String[] args) {
        TimeConsumingTask timeConsumingTask = new TimeConsumingTask();
        Thread thread = new Thread(new TimeConsumingTask());
//        Thread thread = new Thread(timeConsumingTask);
        thread.start();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        timeConsumingTask.cancel();
    }

}


class TimeConsumingTask implements Runnable {

    private volatile boolean toCancel = false;

    @Override
    public void run() {
        while (!toCancel) {
            if (doExecute()) {
                break;
            }
        }
        if (toCancel) {
            System.out.println("task was canceled");
        } else {
            System.out.println("task is done");
        }
    }

    private boolean doExecute() {
        boolean isDone = false;
        System.out.println("executing");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return isDone;
    }

    public void cancel() {
        toCancel = true;
        System.out.println(this + "canceled");
    }


}